package module

// 游戏逻辑类型的核心

import (
	"fmt"
	"gogogo-server/engine/cororpc"
)

type LGLogicCfg struct {
}

// LGLogic 整个框架核心
type LGLogic struct {
	server *cororpc.RPCServer // 作为rpc服务方,被调用
	client *cororpc.RPCClient // 作为rpc发起方时使用
}

func NewLGLogic(coreCfg *LGLogicCfg) *LGLogic {
	c := &LGLogic{}
	c.Init()
	return c
}

func (c *LGLogic) Init() {
	c.server = cororpc.NewServer()
	c.client = cororpc.NewClient()
}

func (c *LGLogic) GetServerCoroRPC() *cororpc.RPCServer {
	return c.server
}

// Run 已经跑在了协程上了
func (c *LGLogic) Run(closeSign chan bool) {
	for {
		select {
		case <-closeSign:
			c.close()
			return
		case ci := <-c.server.CallChan:
			c.server.OnCall(ci)
		case ri := <-c.client.ChanAsyncRet:
			c.client.OnReply(ri)
		}
	}
}

func (c *LGLogic) close() {
}

// PushCoroRequest 发起rpc请求,在调用方调用
func (c *LGLogic) PushCoroRequest(m IModule, arg cororpc.IMessageArg, cb cororpc.TypeRetCallback) {
	toServer := m.GetServerCoroRPC()
	if toServer == nil {
		panic(fmt.Sprintf("要发送的模块[%T]没有CoroRPC, handler id:%v", m, arg.GetMsgId()))
	}
	if cb != nil {
		toServer.PushRPC(c.client.ChanAsyncRet, arg, cb)
	} else {
		toServer.PushPTC(arg)
	}
}
